package com.test.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myprojectoffeixue.R;
import com.macrovideo.pull.lib.PullToRefreshBase.OnRefreshListener;
import com.macrovideo.pull.lib.PullToRefreshListView;
import com.macrovideo.sdk.custom.DeviceInfo;
import com.macrovideo.sdk.defines.Defines;
import com.macrovideo.sdk.defines.ResultCode;
import com.macrovideo.sdk.media.LoginHandle;
import com.macrovideo.sdk.media.LoginHelper;
import com.macrovideo.sdk.tools.DeviceScanner;
import com.macrovideo.sdk.tools.Functions;


@SuppressLint({"HandlerLeak", "InlinedApi"})
public class DeviceListViewActivity extends Activity implements
        OnClickListener, OnItemClickListener, OnItemLongClickListener {
    // ��¼������
    static final int HANDLE_MSG_CODE_LOGIN_RESULT = 0x10;// ��Ϣ�����ʾ�𣺵�¼���
    static final int LOGIN_RESULT_CODE_SUCCESS = 0x0001;// ��¼�ɹ�
    static final int LOGIN_RESULT_CODE_FAIL_NET_DOWN = 0x1001;// ��¼ʧ��-���粻ͨ
    static final int LOGIN_RESULT_CODE_FAIL_NET_POOL = 0x1002;// ��¼�ɹ�-�������ӳ��?
    static final int LOGIN_RESULT_CODE_FAIL_SERVER_OFFLINE = 0x1003;// ��¼ʧ��-������������
    static final int LOGIN_RESULT_CODE_FAIL_VERIFY_FAILED = 0x1004;// ��¼ʧ��-��֤����
    static final int LOGIN_RESULT_CODE_FAIL_USER_NOEXIST = 0x1005;// ��¼ʧ��-�û������?
    static final int LOGIN_RESULT_CODE_FAIL_PWD_ERROR = 0x1006;// ��¼ʧ��-�������?
    static final int LOGIN_RESULT_CODE_FAIL_OLD_VERSON = 0x1007;// ��¼ʧ��-ǰ�˰汾��֧��

    // add by luo 20141016
    static final int HANDLE_MESSAGE_UPDATE_FRESHTIME = 0x20;
    // end add by luo 20141016

    static final int HANDLE_MESSAGE_UPDATE_FRESHFACE = 0x40;// add by luo
    // 20141020

    static final int HANDLE_PREVIEW_LIST_UPDATE = 0x50;// add by luo 20141029

    static final int GET_PREVIEW_LIST_OK = 10;
    static final int GET_PREVIEW_LIST_FAIL_NET_ERR = -11;

    // ҳ������ֵ
    static final int VIEW_INDEX_LOGIN = 1000; //
    static final int VIEW_INDEX_SERVERLIST = 1001; //
    static final int VIEW_INDEX_SEARCH = 1002; //
    static final int VIEW_INDEX_DEVICE_EDIT = 1003; //
    static final int VIEW_INDEX_CONFIG = 1005; //
    static final int VIEW_INDEX_NETWORK_CONFIG = 1006; //
    static final int VIEW_INDEX_RECORD_CONFIG = 1007; //
    static final int VIEW_INDEX_DATETIME_CONFIG = 1008; //
    static final int VIEW_INDEX_USER_CONFIG = 1009; //
    static final int VIEW_INDEX_VER_INFO = 1010; //
    static final int VIEW_INDEX_FILE_LIST = 1011; //

    // �������С�?
    static final int LOGIN_COMMUNICATION_BUFFER_SIZE = 520;
    static final int MR_LOGIN_COMMUNICATION_BUFFER_SIZE = 256;

    // =====add by mai 2015-1-14======
    public static String INTENT_DEVICE_ID = "device"; //
    // =====end add by mai 2015-1-14=====

    public boolean IsEditMode() {
        if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL) {
            return false;
        } else {
            return true;
        }

    }

    static final Object searchLock = new Object();
    // /
    private ListView serverlistView = null;
    private PullToRefreshListView pullToRefreshListView = null;

    private ArrayList<DeviceInfo> demoSeverInfoListDataTemp = new ArrayList<DeviceInfo>();//原始数保存据


    public DeviceListViewAdapter deviceListItemAdapter = null;

    private Button btnSelectAll = null, btnReverSelect = null;

//	private Activity relateAtivity = null;
//	private View contentView = null;


    private int m_loginID = 0;
    private String m_strName = "IPC";
    private String m_strIP = "127.0.0.1";

    private int m_nPort = 8800;
    MulticastLock multicastLock = null;


    private String m_strUsername = "";
    private String m_strPassword = "";
    //
    private Dialog connectingDialog = null;
    private View connectConctentView = null;

    boolean mIsSearchingMode = false;
    private int m_nSearchID = 0;//
    private boolean bIsSearching = false;

    // add by luo 20141015
    private int m_nMsgGetThreadID = 0;//
    // end add by luo 20141015

    // add by luo 20141029
    // 20141016
    // end add by luo 20141029
    // 20141016
    private Button btnDeviceQuickAdd, btnDeviceConfigAdd; //add by mai 2015-3-16
    private Button btnDeviceHotspot; //add by mai 2015-6-16
    private FrameLayout llDeviceQuickAdd; //add by mai 2015-3-16
    private RelativeLayout rlListView;  //add by mai 2015-3-16
    private int m_nIPUpdateID = 0;// add by luo 20141118
    private ImageView ivBack;// add by mai 2015-1-6

    private TextView tvTitle = null;//add by luo 20150504
    private ImageView ivDeviceAdd; // add by mai 2015-2-3
    private LinearLayout llDeviceIDAdd, llSeekFine, llTwoCodeAdd,
            llLocalNetWordSeek, llSmartLink;
    ; // add by mai 2015-2-3
    private LinearLayout llDeviceHotspot; //add by mai 2015-6-16
    private PopupWindow popupWindowAddManu, popuWindowEditDelete, popupWindowEdit, popupWindowAdd; //add by mai 2015-3-10
    private WindowManager windowManager;
    private int width; //
    private int height; //
    boolean bFirsh = true; // add by mai 2015-3-19
    private boolean bCheck = true;
    private ProgressBar searchingProgress;


    private boolean bDemoOrDevice = true; //add by mai 2015-5-11
    private boolean bLanguage = false; // add by mai 2015-6-29

    private ArrayList<DeviceInfo> deviceList = null;  //add by mai 20151211
    private ArrayList<DeviceInfo> deviceIPList = null;  //add by mai 20151211

    private void StartIPUpdateThread() {
        m_nIPUpdateID++;
        closeMulticast();
        openMulticast();
        new IPUpdateThread(m_nIPUpdateID).start();
    }

    private void StopIPUpdateThread() {
        m_nIPUpdateID++;

    }

    protected void onDestroy() {
        multicastLock = null;
        super.onDestroy();

    }

    // /
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_nvplayer_serverlist);
        windowManager = (WindowManager) DeviceListViewActivity.this.getSystemService(
                Context.WINDOW_SERVICE);
        width = windowManager.getDefaultDisplay().getWidth();
        height = windowManager.getDefaultDisplay().getHeight();
        //
        DatabaseManager.InitDataBase(this);
        InitSubView();
        createDialogs();
        LocalDefines.initNoticeSound(DeviceListViewActivity.this);
        LocalDefines.loadAlarmSettings(DeviceListViewActivity.this);
        String locale = Locale.getDefault().getLanguage();

        if (locale.equals("zh")) {
            bLanguage = true;
        } else {
            bLanguage = false;
        }

        if (LocalDefines._isQRResultOK == true) {

            Message msg = handler.obtainMessage();
            msg.arg1 = LocalDefines.HANDLE_SHOW_WINDOW_ADD;

            handler.sendMessage(msg);

        }
    }

    @Override
    public void onPause() {

        super.onPause();


        // end add by luo 20141029
        StopSearchDevice();
        StopAlarmMsgCheck();
        StopIPUpdateThread();
    }

    @Override
    public void onResume() {

        super.onResume();

        if (LocalDefines._isNeedGetPreviewDeviceList) {
            startPreviewListGet();

        }
        StartIPUpdateThread();
        // add by mai 2015-3-24
        if (LocalDefines.B_UPDATE_LISTVIEW && LocalDefines._nListMode != LocalDefines.LIST_MODE_DEMONSTRATE) {

            LocalDefines.B_UPDATE_LISTVIEW = false;
            refleshListView();

        } else {

            if (LocalDefines._nListMode != LocalDefines.LIST_MODE_DEMONSTRATE) {
                updateListView();

            } else {

            }


        }


        if (LocalDefines._nListMode != LocalDefines.LIST_MODE_DEMONSTRATE) {
            // add by luo 20141030
            if (LocalDefines._severInfoListData.size() > 0) {
                //add by mai 2015-3-19
                llDeviceQuickAdd.setVisibility(View.GONE);
                rlListView.setVisibility(View.VISIBLE);
                bCheck = true;
                //end add by mai 2015-3-19
            } else {
                //add by mai 2015-3-19
                llDeviceQuickAdd.setVisibility(View.VISIBLE);
                rlListView.setVisibility(View.GONE);
                bCheck = false;
                //end add by mai 2015-3-19
            }

        }


    }


    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

        _nOnlineStatCheckID++;
        LocalDefines.B_UPDATE_LISTVIEW = true;
        StopSearchDevice();

    }


    // add by luo 20141029

    public void startPreviewListGet() {


    }


    // add by luo 20141015
    public void startAlarmMsgCheck() {


    }

    public void StopAlarmMsgCheck() {

    }

    private void InitSubView() {

        pullToRefreshListView = (PullToRefreshListView)
                findViewById(R.id.pull_refresh_list);


        llDeviceHotspot = (LinearLayout) findViewById(R.id.llDeviceHotspot);
        llDeviceHotspot.setOnClickListener(this);
        llDeviceHotspot.setVisibility(View.GONE);

        searchingProgress = (ProgressBar) findViewById(R.id.searching_progress);

        llDeviceQuickAdd = (FrameLayout) findViewById(R.id.llDeviceQuickConfig);
        //add by mai 2015-6-16
        btnDeviceHotspot = (Button) findViewById(R.id.btnAPHotspot);
        btnDeviceHotspot.setOnClickListener(this);
        btnDeviceHotspot.setVisibility(View.GONE);
        //end add by mai 2015-6-16
        rlListView = (RelativeLayout) findViewById(R.id.rlListView);
        //
        // //@@System.out.println("InitSubView 2");//add for test
        // Set a listener to be invoked when the list should be refreshed.
        pullToRefreshListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here

                if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL) {
                    if (!bIsSearching) {

                        searchingProgress.setVisibility(View.GONE);
                        if (StartSearchDevice() == false) {
                            pullToRefreshListView.onRefreshComplete();
                        }

                    }

                } else {
                    pullToRefreshListView.onRefreshComplete();

                }

            }

        });

        // ==add by mai 2015-1-6=============
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this);
//		btnDemo = (Button) findViewById(R.id.btnDemo);
//		btnDemo.setOnClickListener(this);
        // ==end add by mai 2015-1-6=========

        tvTitle = (TextView) findViewById(R.id.tvTitle);//add by luo 20150604

        // ===add by mai 2015-2-3====
        ivDeviceAdd = (ImageView) findViewById(R.id.ivDeviceAdd);
        ivDeviceAdd.setOnClickListener(this);
        // ===end add by mai 2015-2-3===
        pullToRefreshListView.showBackToTopView(false);
        serverlistView = pullToRefreshListView.getRefreshableView();
        serverlistView.setOnItemLongClickListener(this);
        setListviewOnScrollListener();

        tvTitle.setText(getString(R.string.myDevice));//add by luo 20150604

        if (LocalDefines._nListMode == LocalDefines.LIST_MODE_EDIT) {

            if (LocalDefines._severInfoListData == null
                    || LocalDefines._severInfoListData.size() == 0) {

                LocalDefines._nListMode = LocalDefines.LIST_MODE_NORMAL;

                if (pullToRefreshListView != null) {
                    pullToRefreshListView.showBackToTopView(true);
                    pullToRefreshListView.visibleHeaderLayout(true);
                }
                updateListView();

            } else {

                LocalDefines._nListMode = LocalDefines.LIST_MODE_EDIT;

                if (pullToRefreshListView != null) {
                    pullToRefreshListView.showBackToTopView(false);
                    pullToRefreshListView.visibleHeaderLayout(false);
                }
                updateListView();

            }

        } else if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL) {

            bFirsh = true;
            ivBack.setVisibility(View.GONE);

            if (LocalDefines.B_UPDATE_LISTVIEW) {
                refleshListView();

                LocalDefines.B_UPDATE_LISTVIEW = false;

            } else {

                updateListView();
            }

            ivDeviceAdd.setImageResource(R.drawable.more_function_btn);

        } else if (LocalDefines._nListMode == LocalDefines.LIST_MODE_DEMONSTRATE) {
            tvTitle.setText(getString(R.string.demoPoint));//add by luo 20150604
            bFirsh = false;

            ivBack.setVisibility(View.VISIBLE);
            ivDeviceAdd.setImageResource(R.drawable.fresh_btn);
            showDemonstrateListView();

        }
    }

    private void createDialogs() {

        // create connecting activity dialog
        connectConctentView = LayoutInflater.from(DeviceListViewActivity.this).inflate(
                R.layout.logindialog, null);
        connectingDialog = new Dialog(DeviceListViewActivity.this, R.style.selectorDialog);
        connectingDialog.setContentView(connectConctentView);
        connectingDialog.setOnShowListener(new DialogInterface.OnShowListener() {

            @Override
            public void onShow(DialogInterface dialog) {
                // TODO Auto-generated method stub
                TextView tv = (TextView) connectConctentView
                        .findViewById(R.id.loginText);

                if (mIsSearchingMode) {
                    tv.setText(getString(R.string.searching));
                } else {
                    tv.setText(getString(R.string.loading));
                }

            }
        });

        connectingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub
                if (mIsSearchingMode) {
                    m_nSearchID++;//
                    bIsSearching = false;
                } else {
                    m_loginID++;
                }

                mIsSearchingMode = false;
            }

        });
        connectingDialog.setCanceledOnTouchOutside(true);
        connectingDialog.setCancelable(true);
    }
    // /
    private class DeviceListViewAdapter extends BaseAdapter {

        private class ItemViewHolder {
            ImageView btnFace;
            TextView tvName;
            TextView tvState;
            ImageView ivDeviceState;
            ImageView ivAlarm;
            LinearLayout llAlarm;
            LinearLayout llDeviceState; // add by mai 2015-7-7


        }

        private ArrayList<HashMap<String, Object>> mAppList;
        private LayoutInflater mInflater;
        private Context mContext;
        private String[] keyString;
        private int[] valueViewID;
        private ItemViewHolder holder;

        public DeviceListViewAdapter(Context c,
                                     ArrayList<HashMap<String, Object>> appList, int resource,
                                     String[] from, int[] to) {
            mAppList = appList;
            mContext = c;
            mInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            keyString = new String[from.length];
            valueViewID = new int[to.length];
            System.arraycopy(from, 0, keyString, 0, from.length);
            System.arraycopy(to, 0, valueViewID, 0, to.length);
        }

        @Override
        public int getCount() {
            return mAppList.size();
        }

        @Override
        public Object getItem(int position) {
            return mAppList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressWarnings("deprecation")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView != null) {
                holder = (ItemViewHolder) convertView.getTag();
            } else {
                convertView = mInflater
                        .inflate(R.layout.server_list_item, null);
                holder = new ItemViewHolder();
                holder.btnFace = (ImageView) convertView
                        .findViewById(valueViewID[0]);
                holder.tvName = (TextView) convertView
                        .findViewById(valueViewID[1]);
                holder.tvState = (TextView) convertView
                        .findViewById(valueViewID[2]);
                holder.llAlarm = (LinearLayout) convertView
                        .findViewById(valueViewID[3]);
                holder.ivAlarm = (ImageView) convertView
                        .findViewById(valueViewID[4]);
                holder.ivDeviceState = (ImageView) convertView
                        .findViewById(valueViewID[5]);
                holder.llDeviceState = (LinearLayout) convertView //add by mai 2015-7-7
                        .findViewById(valueViewID[6]); ///////////////////////

                convertView.setTag(holder);
            }

            // /

            HashMap<String, Object> map = mAppList.get(position);
            if (map != null) {

                // //

//				int nIndex = (Integer) map.get("index");
                DeviceInfo servernfo = null;

                if (LocalDefines._nListMode == LocalDefines.LIST_MODE_DEMONSTRATE) {// modify
                    // by
                    // luo
                    // 20141028

                    if (LocalDefines._demoSeverInfoListData != null && position >= 0
                            && position < LocalDefines._demoSeverInfoListData.size()) {
                        servernfo = LocalDefines._demoSeverInfoListData.get(position);

                    }


                } else {

                    if (LocalDefines._severInfoListData != null && position >= 0
                            && position < LocalDefines._severInfoListData.size()) {
                        servernfo = LocalDefines._severInfoListData.get(position);

                    }
                }

                if (servernfo == null) {
                    return null;
                }

                // //
                String name = servernfo.getStrName();

                int nSaveType = servernfo.getnSaveType();// (Integer)map.get("SaveType");

                holder.tvName.setVisibility(View.VISIBLE);
                holder.llAlarm.setVisibility(View.VISIBLE);
                Log.d("deviced", "" + servernfo.getnDevID());
                //-----------------------------------------------------------------deviced---------------------------

                if (name == null || name.length() <= 0) {
                    holder.tvName.setText("" + servernfo.getnDevID());
                } else {
                    holder.tvName.setText(name);
                }


                if (nSaveType == Defines.SERVER_SAVE_TYPE_ADD) {
                    holder.tvName.setTextColor(Color.BLUE);
                } else {
                    holder.tvName.setTextColor(Color.BLACK);
                }

                // === add by mai 2014-12-15=======
                holder.llAlarm.setOnClickListener(new ListViewButtonListener(
                        position));
                // ===end add by mai 2014-12-15=======

                // add by luo 20141027
                if (LocalDefines._nListMode == LocalDefines.LIST_MODE_DEMONSTRATE) {

                    // ===add by mai 2014-12-17===========
                    holder.tvState.setVisibility(View.GONE);
                    holder.llAlarm.setVisibility(View.GONE);
                    holder.ivDeviceState.setVisibility(View.GONE); // add by mai 2015-6-18
                    holder.llDeviceState.setVisibility(View.GONE); // add by mai 2015-7-7
                    // ====end add by mai 2014-12-17=========

                } else {
                    //modify by luo 20150711

                    if (servernfo.getnOnLineStat() == Defines.ON_LINE_STAT_OFF) {
                        holder.tvState.setText(getString(R.string.strWanOffline));
                        holder.ivDeviceState.setImageResource(R.drawable.offline);
                    } else if (servernfo.getnOnLineStat() == Defines.ON_LINE_STAT_LAN) {
                        holder.tvState.setText(getString(R.string.strLanOnline));
                        holder.ivDeviceState.setImageResource(R.drawable.online);
                    } else if (servernfo.getnOnLineStat() == Defines.ON_LINE_STAT_WAN) {
                        holder.tvState.setText(getString(R.string.strWanOnline));
                        holder.ivDeviceState.setImageResource(R.drawable.online);
                    } else {
                        holder.tvState.setText(getString(R.string.strOnlineChecking));
                        holder.ivDeviceState.setImageResource(R.drawable.online);
                    }

                }

                if (servernfo.getlLastMsgFreshTime() <= 0) {

                    holder.llAlarm.setVisibility(View.INVISIBLE);

                } else {

                    holder.llAlarm.setVisibility(View.VISIBLE);


                    if (servernfo.getnNewMsgCount() > 0) {

                        holder.ivAlarm.setImageBitmap(Functions.readBitMap(DeviceListViewActivity.this, R.drawable.alarm_message_2));
                    } else {

                        holder.ivAlarm.setImageBitmap(Functions.readBitMap(DeviceListViewActivity.this, R.drawable.alarm_message_1));
                    }
                }

                // add by luo 20141008
                Bitmap faceImage = null;
                faceImage = servernfo.getFaceImage();

                if (faceImage != null) {
                    holder.btnFace.setImageDrawable(new BitmapDrawable(faceImage));

                } else {

                    holder.btnFace.setImageDrawable(null);

                }

            }

            return convertView;
        }

        class ListViewButtonListener implements OnClickListener {
            private int position;

            ListViewButtonListener(int pos) {
                position = pos;
            }

            @Override
            public void onClick(View v) {

                // //@@System.out.println("onClick: "+ v.getId ());//add for test

                int vid = v.getId();

                if (vid == holder.llAlarm.getId()) {
                    onShowAlarmMessage(position);
                }
                // ===end add by mai 2015-1-6=======
            }
        }
    }

    private void setListviewOnScrollListener() {

        if (serverlistView == null)
            return;

        serverlistView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                    // add by luo 20141010
                    if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL) {
                        LocalDefines._listviewFisrtPosition = serverlistView
                                .getFirstVisiblePosition();

                    }
                    // end add by luo 20141010
                }

            }


            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int nSelectIndex,
                            long arg3) {
        // TODO Auto-generated method stub

        if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL) {
            if (LocalDefines._severInfoListData != null && nSelectIndex >= 0
                    && nSelectIndex < LocalDefines._severInfoListData.size()) {
                DeviceInfo info = LocalDefines._severInfoListData.get(nSelectIndex);

                StartLogin(info);

                //
                LocalDefines._PlatbackListviewSelectedPosition = nSelectIndex;
            }
        } else if (LocalDefines._nListMode == LocalDefines.LIST_MODE_DEMONSTRATE) {

            if (LocalDefines._demoSeverInfoListData != null && nSelectIndex >= 0 && nSelectIndex < LocalDefines._demoSeverInfoListData.size()) {
                DeviceInfo info = LocalDefines._demoSeverInfoListData
                        .get(nSelectIndex);

                LocalDefines._DemoMRServer = info.getStrMRServer();
                LocalDefines._DemoMRPort = info.getnMRPort();
                StartLogin(info);
            }
        } else if (LocalDefines._nListMode == LocalDefines.LIST_MODE_EDIT) {// ���ڱ༭�б�
            if (LocalDefines._severInfoListData != null && nSelectIndex >= 0
                    && nSelectIndex < LocalDefines._severInfoListData.size()) {
                DeviceInfo info = LocalDefines._severInfoListData.get(nSelectIndex);

            }
        }

    }

    public void ShowServerListMode() {
        if (LocalDefines._nListMode == LocalDefines.LIST_MODE_DEMONSTRATE) {
            tvTitle.setText(getString(R.string.myDevice));//add by luo 20150604
            LocalDefines._nListMode = LocalDefines.LIST_MODE_NORMAL;
            if (pullToRefreshListView != null) {
                pullToRefreshListView.showBackToTopView(true);
                pullToRefreshListView.visibleHeaderLayout(true);
            }

            refleshListView();

        } else {
            showNormalListView();
        }

    }

    public void StartLogin(DeviceInfo info) {

        // add by luo 20141030
        if (bIsSearching) {
            StopSearchDevice();
        }
        // end add by luo 20141030

        if (info == null)
            return;
        try {
            if (!Functions.isNetworkAvailable(DeviceListViewActivity.this
                    .getApplicationContext())) {

                Toast toast = Toast.makeText(
                        DeviceListViewActivity.this.getApplicationContext(),
                        getString(R.string.toast_network_unreachable),
                        Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
        } catch (Exception e) {
        }

        m_loginID++;

        connectingDialog.show();

        int nServerType = LocalDefines.SERVER_TYPE_IP;
        if (info.getnSaveType() == Defines.SERVER_SAVE_TYPE_ADD) {

            if (Functions.isIpAddress(info.getStrIP())) {
                nServerType = LocalDefines.SERVER_TYPE_IP;
            } else {
                if (!Functions.hasDot(info.getStrIP())) {
                    info.setStrIP(info.getStrIP() + ".nvdvr.net");
                }
                nServerType = LocalDefines.SERVER_TYPE_DOMAIN;
            }
        }

        m_strIP = info.getStrIP();
        m_nPort = info.getnPort();


        if (info.getStrUsername() == null || info.getStrUsername().length() <= 0) {
            m_strUsername = "admin";
            m_strPassword = "";
        } else {
            m_strUsername = info.getStrUsername();
            m_strPassword = info.getStrPassword();
        }
        m_strName = info.getStrName();

        new LoginThread(handler, info, m_loginID).start();


    }

    //提示窗口
    public void ShowAlert(String title, String msg) {

        if (hasWindowFocus()) {
            new AlertDialog.Builder(this)//
                    .setTitle(title).setMessage(msg)
                    .setIcon(R.drawable.device_bg)
                    .setPositiveButton(getString(R.string.alert_btn_OK), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            setResult(Activity.RESULT_OK);
                        }

                    }).show();

        }
    }


    private void showNormalListView() {

        tvTitle.setText(getString(R.string.myDevice));//add by luo 20150604
        LocalDefines._nListMode = LocalDefines.LIST_MODE_NORMAL;
        if (pullToRefreshListView != null) {
            pullToRefreshListView.showBackToTopView(true);
            pullToRefreshListView.visibleHeaderLayout(true);
        }

        initAlarmList();// add by luo 20141018
        updateListView();

    }


    private void showDemonstrateListView() {// add by luo 20141027

        if (bIsSearching) {
            StopSearchDevice();
        }

        LocalDefines._nListMode = LocalDefines.LIST_MODE_DEMONSTRATE;

        tvTitle.setText(getString(R.string.demoPoint));//add by luo 20150604

        if (pullToRefreshListView != null) {
            pullToRefreshListView.showBackToTopView(false);
            pullToRefreshListView.visibleHeaderLayout(false);
        }

        updateDemoListView();
    }

    private void onSelectChange() {// add by luo 20141016

        if (LocalDefines._severInfoListData.size() <= 0) {

            Drawable image = getResources().getDrawable(
                    R.drawable.check_normal_btn);
            int nHeigth = (int) (btnSelectAll.getHeight() * 0.8);
            int y = (btnSelectAll.getHeight() - nHeigth) / 2;

            btnSelectAll.setCompoundDrawablesWithIntrinsicBounds(image, null,
                    null, null);
            btnReverSelect.setCompoundDrawablesWithIntrinsicBounds(image, null,
                    null, null);
            return;
        }

        boolean bIsSelectAll = true;
        boolean bDisselectAll = true;
        DeviceInfo info = null;
        for (int i = 0; i < LocalDefines._severInfoListData.size(); i++) {

            info = LocalDefines._severInfoListData.get(i);
            if (info != null) {
                if (info.isCheck()) {
                    bDisselectAll = false;
                } else {
                    bIsSelectAll = false;
                }

            }
        }

        if (bIsSelectAll) {
            Drawable image = getResources().getDrawable(
                    R.drawable.check_save_btn);
            int nHeigth = (int) (btnSelectAll.getHeight() * 0.8);
            int y = (btnSelectAll.getHeight() - nHeigth) / 2;
            // image.setBounds(1, y, nHeigth, btnSelectAll.getHeight()-y);
            btnSelectAll.setCompoundDrawablesWithIntrinsicBounds(image, null,
                    null, null);
        } else {


            Drawable image = getResources().getDrawable(
                    R.drawable.check_normal_btn);
            int nHeigth = (int) (btnSelectAll.getHeight() * 0.8);
            int y = (btnSelectAll.getHeight() - nHeigth) / 2;
            // image.setBounds(1, y, nHeigth, btnSelectAll.getHeight()-y);
            btnSelectAll.setCompoundDrawablesWithIntrinsicBounds(image, null,
                    null, null);
        }
        if (bDisselectAll) {
            Drawable image = getResources().getDrawable(
                    R.drawable.check_save_btn);
            int nHeigth = (int) (btnReverSelect.getHeight() * 0.8);
            int y = (btnReverSelect.getHeight() - nHeigth) / 2;
            // image.setBounds(1, y, nHeigth, btnSelectAll.getHeight()-y);
            btnReverSelect.setCompoundDrawablesWithIntrinsicBounds(image, null,
                    null, null);
        } else {
            Drawable image = getResources().getDrawable(
                    R.drawable.check_normal_btn);
            int nHeigth = (int) (btnReverSelect.getHeight() * 0.8);
            int y = (btnReverSelect.getHeight() - nHeigth) / 2;
            // image.setBounds(1, y, nHeigth, btnSelectAll.getHeight()-y);
            btnReverSelect.setCompoundDrawablesWithIntrinsicBounds(image, null,
                    null, null);
        }

    }


    private void initAlarmList() {
        // add by luo 20141018
        LocalDefines._severInfoListDataForAlarm.clear();
        if (LocalDefines._severInfoListData.size() > 0) {
            DeviceInfo info = null;
            ServerInfoForAlarm saInfo = null;
            boolean isNew = false;
            for (int i = LocalDefines._severInfoListData.size() - 1; i >= 0; i--) {
                if (i >= LocalDefines._severInfoListData.size()) break;
                info = LocalDefines._severInfoListData.get(i);
                if (info != null && info.getnDevID() > 0) {
                    if (LocalDefines._severInfoListDataForAlarm.size() <= 0) {
                        LocalDefines._severInfoListDataForAlarm
                                .add(new ServerInfoForAlarm(info.getnID(), info
                                        .getnDevID(), info.getnNewMsgCount(),
                                        info.getStrUsername(), info
                                        .getStrPassword(), info
                                        .getlLastMsgFreshTime(), info
                                        .getlLastMsgGetTime()));
                    } else {
                        isNew = true;
                        for (int j = LocalDefines._severInfoListDataForAlarm.size() - 1; j >= 0; j--) {
                            saInfo = LocalDefines._severInfoListDataForAlarm.get(j);
                            if (saInfo.getnDevID() == info.getnDevID()
                                    && saInfo.getStrUsername() == info
                                    .getStrUsername()
                                    && saInfo.getStrPassword() == info
                                    .getStrDomain()) {
                                isNew = false;
                                break;
                            }
                        }
                        if (isNew) {
                            LocalDefines._severInfoListDataForAlarm
                                    .add(new ServerInfoForAlarm(info.getnID(),
                                            info.getnDevID(), info
                                            .getnNewMsgCount(), info
                                            .getStrUsername(), info
                                            .getStrPassword(), info
                                            .getlLastMsgFreshTime(),
                                            info.getlLastMsgGetTime()));
                        }
                    }

                }
            }
        }
        // end add by luo 20141018
    }

    //点击方法


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (v == null)
            return;
        switch (v.getId()) {

            // == add by mai 2014-12-15=====
            case R.id.ivDeviceAdd:
                if (bFirsh) {

                    showAddNamu(v);

                } else {

                    searchingProgress.setVisibility(View.VISIBLE); //add by mai 2015-3-23
                    startPreviewListGet();
                }

                break;

            //二维码入口
            case R.id.llDeviceIDAdd:
                if (bIsSearching) {
                    searchingProgress.setVisibility(View.GONE);
                    StopSearchDevice();
                }
                deviceIDAdd();

                popupWindowAddManu.dismiss();
                break;

            // ===end add by mai 2015-2-3==
            case R.id.llLocalNetWordSeek:
                if (bIsSearching) {
                    searchingProgress.setVisibility(View.GONE);
                    StopSearchDevice();
                }

                searchingProgress.setVisibility(View.VISIBLE); //add by mai 2015-3-23
                StartSearchDevice();
                popupWindowAddManu.dismiss();
                break;


            case R.id.llSmartLink:
                if (bIsSearching) {
                    searchingProgress.setVisibility(View.GONE);
                    StopSearchDevice();
                }
                Intent intentSoundWave = new Intent(DeviceListViewActivity.this, SmartLinkQuickWifiConfigActivity.class);
                startActivity(intentSoundWave);
                popupWindowAddManu.dismiss();

                break;


            case R.id.btnAPHotspot:
                if (bIsSearching) {
                    searchingProgress.setVisibility(View.GONE);
                    StopSearchDevice();
                }

                break;

            case R.id.llDeviceHotspot:
                if (bIsSearching) {
                    searchingProgress.setVisibility(View.GONE);
                    StopSearchDevice();
                }
                break;
            case R.id.llTWoCodeAdd:
                if (bIsSearching) {
                    searchingProgress.setVisibility(View.GONE);
                    StopSearchDevice();
                }

                Intent intent3 = new Intent(DeviceListViewActivity.this, MipcaActivityCapture.class);
                startActivity(intent3);

                break;
            default:
                break;
        }

    }

    private void showAddNamu(View v) {

        LayoutInflater layoutInflater = (LayoutInflater) DeviceListViewActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(
                R.layout.manu_device_add_popuwindow, null);

        llDeviceIDAdd = (LinearLayout) view.findViewById(R.id.llDeviceIDAdd);
        llDeviceIDAdd.setOnClickListener(this);
        llTwoCodeAdd = (LinearLayout) view.findViewById(R.id.llTWoCodeAdd);
        llTwoCodeAdd.setOnClickListener(this);
        llLocalNetWordSeek = (LinearLayout) view.findViewById(R.id.llLocalNetWordSeek);
        llLocalNetWordSeek.setOnClickListener(this);
        //add soundWaveConfig by mai 2015-4-2
        llSmartLink = (LinearLayout) view.findViewById(R.id.llSmartLink);
        llSmartLink.setOnClickListener(this);
        int padding_in_dp = 340;
        int paddingWidth = 170;
        final float scale = getResources().getDisplayMetrics().density;
        int padding_in_px = (int) (padding_in_dp * scale + 0.5f);
        int paddingWidth2 = (int) (paddingWidth * scale + 0.5f);
        popupWindowAddManu = new PopupWindow(view, paddingWidth2, padding_in_px);
        popupWindowAddManu.setFocusable(true);
        popupWindowAddManu.setOutsideTouchable(true);
        popupWindowAddManu.setBackgroundDrawable(new BitmapDrawable());
        popupWindowAddManu.setAnimationStyle(R.style.popupwindow_relevance_anim);
        popupWindowAddManu.showAsDropDown(v);
    }


    private void deviceIDAdd() {
        Log.w("test ", "deviceIDAdd");

        LayoutInflater layoutInflater = (LayoutInflater) DeviceListViewActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.add_id_device_popuwindow, null);


        final EditText etDeviceIDAdd = (EditText) view
                .findViewById(R.id.etDeviceIDAdd);
        final EditText etUserNameAdd = (EditText) view
                .findViewById(R.id.etUserNameAdd);
        final EditText etPasswordAdd = (EditText) view
                .findViewById(R.id.etPasswordAdd);
        ImageView ivDeviceAddBack = (ImageView) view
                .findViewById(R.id.ivDeviceAddBack);
        Button btnDeviceManageAdd = (Button) view
                .findViewById(R.id.btnDeviceManageAdd);

        etUserNameAdd.setText("admin");
        ivDeviceAddBack.setOnClickListener(

                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {

                        if (popupWindowAdd != null) {
                            popupWindowAdd.dismiss();
                        }


                    }
                });


        btnDeviceManageAdd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                String strDeviceID = etDeviceIDAdd.getText().toString().trim();
                String strUserName = etUserNameAdd.getText().toString().trim();
                String strPassword = etPasswordAdd.getText().toString().trim();


                if (strDeviceID != null && strDeviceID.length() > 0 && strDeviceID.length() <= 11) {
                    int id = Integer.parseInt(strDeviceID);


                    DeviceInfo info = new DeviceInfo(-1, id, strDeviceID,
                            "192.168.1.1", 8800, strUserName, strPassword, "",
                            id + Defines.MV_DOMAIN_SUFFIX, Defines.SERVER_SAVE_TYPE_ADD);
                    boolean bResult = false;
                    if (!DatabaseManager.IsInfoExist(info)) { //����豸������?
                        Log.w("aa", "AddServerInfo");
                        bResult = DatabaseManager.AddServerInfo(info);
                    } else {
                        Log.w("aa", "UpdateServerInfo");
                        bResult = DatabaseManager.UpdateServerInfo(info);
                    }


                    if (bResult) {

                        Toast.makeText(DeviceListViewActivity.this, getString(R.string.deviceAddSucceed),
                                Toast.LENGTH_SHORT).show();


                        refleshListView();
                        LocalDefines.isDeviceListSet = false;
                        LocalDefines.reloadDeviceInfoList();
                        LocalDefines.nClientDeviceSettingThreadID++;

                        if (popupWindowAdd != null) {
                            popupWindowAdd.dismiss();
                        }

                    } else {


                        Toast.makeText(DeviceListViewActivity.this, getString(R.string.deviceAddFail),
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(DeviceListViewActivity.this, getString(R.string.deviceAddEditTextInputType),
                            Toast.LENGTH_SHORT).show();

                }

            }
        });

        if (LocalDefines._isQRResultOK == true) {

            if (LocalDefines._nQRResultDevice > 0) {
                etDeviceIDAdd.setText("" + LocalDefines._nQRResultDevice);
            }

            LocalDefines._isQRResultOK = false;
            LocalDefines._nQRResultDevice = 0;


        }

        int nSize = LayoutParams.MATCH_PARENT;
        if (nSize < 200) {
            popupWindowAdd = new PopupWindow(view, nSize, nSize);
            popupWindowAdd.setFocusable(true);
            popupWindowAdd.setOutsideTouchable(true);
            popupWindowAdd.setBackgroundDrawable(new ColorDrawable(0x00000000));
            popupWindowAdd.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);

        } else {
            popupWindowAdd = new PopupWindow(view, nSize, nSize);
            popupWindowAdd.setFocusable(true);
            popupWindowAdd.setOutsideTouchable(true);
            popupWindowAdd.setBackgroundDrawable(new ColorDrawable(0x00000000));
            popupWindowAdd.showAsDropDown(view);
        }


    }


    @SuppressWarnings("deprecation")
    private void setEditDelete(View v, final DeviceInfo info, final int index) {

        LayoutInflater layoutInflater = LayoutInflater.from(DeviceListViewActivity.this);
        View view = layoutInflater.inflate(R.layout.popupwind_edit_delete,
                null);

        Button btnEdit = (Button) view.findViewById(R.id.btnEdit);
        Button btnDelete = (Button) view.findViewById(R.id.btnDelete);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
        Button btnAllDelete = (Button) view.findViewById(R.id.btnAllDelete);


        btnEdit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                setEditDevice(info);

                if (popuWindowEditDelete != null) {
                    popuWindowEditDelete.dismiss();
                }


            }
        });


        btnDelete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                boolean bDelete = false;

                bDelete = DatabaseManager.DeleteServerInfo(info);
                if (bDelete) {
                    //modify by luo 20150714
                    if (index < LocalDefines._severInfoListData.size() && index < LocalDefines._severInfoWithoutImageListData.size()) {
                        LocalDefines._severInfoListData.remove(index);  //add by mai 2015-7-2 ֱ��ɾ���б�������?

                        LocalDefines._severInfoWithoutImageListData.remove(index);
                        LocalDefines.isDeviceListSet = false;
                        LocalDefines.nClientDeviceSettingThreadID++;


                    }

                    //end modify by luo 20150714

                    updateListView();
                    Toast.makeText(DeviceListViewActivity.this, getString(R.string.deviceDelete), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(DeviceListViewActivity.this, getString(R.string.deleteFail), Toast.LENGTH_SHORT).show();
                }

                if (popuWindowEditDelete != null) {
                    popuWindowEditDelete.dismiss();
                }
            }
        });


        btnAllDelete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {


                LocalDefines.B_UPDATE_LISTVIEW = true;

                if (popuWindowEditDelete != null) {
                    popuWindowEditDelete.dismiss();
                }

            }
        });


        btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (popuWindowEditDelete != null) {
                    popuWindowEditDelete.dismiss();
                }


            }
        });


        popuWindowEditDelete = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        popuWindowEditDelete.setFocusable(true);
        popuWindowEditDelete.setOutsideTouchable(true);
        popuWindowEditDelete.setBackgroundDrawable(new BitmapDrawable());
        popuWindowEditDelete.showAsDropDown(view);
    }


    @SuppressWarnings("deprecation")
    private void setEditDevice(final DeviceInfo info) {
        LayoutInflater layoutInflater = (LayoutInflater) DeviceListViewActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.activity_nvplayer_device_edit,
                null);
        ImageView ivDevice = (ImageView) view.findViewById(R.id.btn_device_edit_cancel);
        final TextView etDeviceID = (TextView) view.findViewById(R.id.et_device_edit_dev_id);
        final EditText etDeviceName = (EditText) view.findViewById(R.id.et_device_edit_name);
        final EditText etUserName = (EditText) view.findViewById(R.id.et_device_edit_username);
        final EditText etPassword = (EditText) view.findViewById(R.id.et_device_edit_password);
        final Button btnDeviceEditSave = (Button) view.findViewById(R.id.btn_device_edit_save2);

        etDeviceID.setText(info.getnDevID() + "");
        if (info.getStrName() != null && info.getStrName().length() > 0) {
            etDeviceName.setText(info.getStrName());
        } else {
            etDeviceName.setText(null);
        }

        etUserName.setText(info.getStrUsername());
        etPassword.setText(info.getStrPassword());


        ivDevice.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (popupWindowEdit != null) {
                    popupWindowEdit.dismiss();
                }

            }
        });

        btnDeviceEditSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {


                String strName = etDeviceName.getText().toString().trim();
                String strUsername = etUserName.getText().toString().trim();
                String strPassword = etPassword.getText().toString();
                String strID = etDeviceID.getText().toString().trim();

                if (strUsername == null || strUsername.length() == 0) {
                    ShowAlert(getString(R.string.alert_title), getString(R.string.notice_UsernameIsNULL));
                    return;
                }
                if (strID == null || strID.length() == 0) {
                    ShowAlert(getString(R.string.alert_title), getString(R.string.notice_DevIsNULL));
                    return;
                }
                int nDeviceID = 0;
                try {
                    nDeviceID = Integer.parseInt(etDeviceID.getText().toString());
                } catch (Exception e) {

                }

                DeviceInfo infos = new DeviceInfo(info.getnID(), nDeviceID, strName, info.getStrIP(), info.getnPort(), strUsername, strPassword, info.getStrDomain(), info.getnSaveType(), "", 0);
                boolean bResult = DatabaseManager.modifyServerInfo(infos);


                if (bResult) {
                    refleshListView();

                    if (popupWindowEdit != null) {
                        popupWindowEdit.dismiss();
                    }
                } else {

                }


            }
        });


        popupWindowEdit = new PopupWindow(view, width, height);
        popupWindowEdit.setFocusable(true); // ʹ��۽�?
        popupWindowEdit.setOutsideTouchable(true); // ����������������ʧ
        popupWindowEdit.setBackgroundDrawable(new BitmapDrawable()); // ������ؼ�BackҲ�ܹ�ʹ����ʧ������Ӱ�챳��
        popupWindowEdit.showAsDropDown(view);

    }


    // ===end add by mai 2015-2-3===

    //������ʾ���б�
    public void updateDemoListView() {// add by luo 20141027

        bDemoOrDevice = false; // add by mai 2015-5-11

        if (LocalDefines._demoSeverInfoListData != null && LocalDefines._demoSeverInfoListData.size() > 0) {
            ArrayList<HashMap<String, Object>> listItem2 = new ArrayList<HashMap<String, Object>>();
            DeviceInfo info = null;
            for (int i = 0; i < LocalDefines._demoSeverInfoListData.size(); i++) {
                info = LocalDefines._demoSeverInfoListData.get(i);

                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("index", (Integer) i);
                map.put("ID", (Integer) info.getnID());
                map.put("DevID", (Integer) info.getnDevID());
                map.put("server", info);
                listItem2.add(map);

            }

            // �����������Item�Ͷ�̬�����Ӧ��Ԫ��?

            deviceListItemAdapter = new DeviceListViewAdapter(DeviceListViewActivity.this, listItem2,// ����?
                    R.layout.server_list_item,// ListItem��XMLʵ��

                    // ��̬������ImageItem��Ӧ������

                    new String[]{"ItemBtnFace", "ItemTitleName",
                            "ItemTitleID", "ItemBtnAlarm",
                            "ItemTrHomeListing", "ItemLlDeviceState", "ItemLlDeviceState"},

                    // ImageItem��XML�ļ������һ��ImageView,����TextView ID

                    new int[]{R.id.item_face, R.id.ItemTitleName,
                            R.id.ItemTitleID, R.id.llAlarm, R.id.ivAlarm, R.id.ivDeviceState, R.id.llDeviceState}


            );

            if (serverlistView == null) {
                serverlistView = pullToRefreshListView.getRefreshableView();
                //serverlistView = pullToRefreshListView;
                setListviewOnScrollListener();

            }

            if (serverlistView != null) {
                serverlistView.setCacheColorHint(Color.TRANSPARENT);
                // ��Ӳ������?
                serverlistView.setAdapter(deviceListItemAdapter);
                // ��ӵ��
                serverlistView.setOnItemClickListener(this);


                // add by luo 20141010
                if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL
                        && LocalDefines._listviewFisrtPosition > 0) {


                    serverlistView.setSelection(LocalDefines._listviewFisrtPosition);
                } else {
                    serverlistView.setSelection(0);
                }
                // end add by luo 20141010

            }

        } else {

            if (serverlistView == null) {
                serverlistView = pullToRefreshListView.getRefreshableView();
                //serverlistView = pullToRefreshListView;
                setListviewOnScrollListener();

            }
            if (serverlistView != null) {
                // ��Ӳ������?
                serverlistView.setAdapter(null);
            }
        }
    }

    //
    public void loadDeviceInfoList() {

        LocalDefines.loadDeviceList(false);

        initAlarmList();// add by luo 20141018
    }

    //�����豸�б�
    public void updateListView() {


        bDemoOrDevice = true; // add by mai 2015-5-11
        if (LocalDefines._severInfoListData != null && LocalDefines._severInfoListData.size() > 0) {
            ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

            DeviceInfo info = null;
            for (int i = LocalDefines._severInfoListData.size() - 1; i >= 0; i--) {
                if (i >= LocalDefines._severInfoListData.size()) break;
                info = LocalDefines._severInfoListData.get(i);

                HashMap<String, Object> map = new HashMap<String, Object>();

                map.put("index", (Integer) i);
                map.put("ID", (Integer) info.getnID());
                map.put("DevID", (Integer) info.getnDevID());
                map.put("server", info);
                listItem.add(map);

            }

            // �����������Item�Ͷ�̬�����Ӧ��Ԫ��?

//			itemsMap.clear();
            deviceListItemAdapter = new DeviceListViewAdapter(DeviceListViewActivity.this,
                    listItem,// ����?

                    R.layout.server_list_item,// ListItem��XMLʵ��

                    // ��̬������ImageItem��Ӧ������

                    new String[]{"ItemBtnFace", "ItemTitleName",
                            "ItemTitleID", "ItemBtnAlarm",
                            "ItemTrHomeListing", "ItemLlDeviceState", "ItemLlDeviceState"},

                    // ImageItem��XML�ļ������һ��ImageView,����TextView ID

                    new int[]{R.id.item_face, R.id.ItemTitleName,
                            R.id.ItemTitleID, R.id.llAlarm, R.id.ivAlarm, R.id.ivDeviceState, R.id.llDeviceState}

            );

            if (serverlistView == null) {
                serverlistView = pullToRefreshListView.getRefreshableView();
                //	serverlistView = pullToRefreshListView;
                setListviewOnScrollListener();
            }

            if (serverlistView != null) {
                serverlistView.setCacheColorHint(Color.TRANSPARENT);
                // ��Ӳ������?
                serverlistView.setAdapter(deviceListItemAdapter);
                // ��ӵ��
                serverlistView.setOnItemClickListener(this);
                // add by luo 20141010
                if (LocalDefines._nListMode == LocalDefines.LIST_MODE_NORMAL
                        && LocalDefines._listviewFisrtPosition > 0) {

//					//@@System.out.println("Defines._listviewFisrtPosition = "
//							+ Defines._listviewFisrtPosition);// add for test

                    serverlistView.setSelection(LocalDefines._listviewFisrtPosition);
                } else {
                    serverlistView.setSelection(0);
                }
                // end add by luo 20141010
            }

        } else {

            if (serverlistView == null) {
                serverlistView = pullToRefreshListView.getRefreshableView();
                //	serverlistView = pullToRefreshListView;
                setListviewOnScrollListener();
            }
            if (serverlistView != null) {
                // ��Ӳ������?
                serverlistView.setAdapter(null);
            }
        }
    }


    public void refleshListView() {
//		//@@System.out.println("refleshListView start ");// add for test

        LocalDefines.loadDeviceList(false);

        // add by luo 20141030
        if (LocalDefines._severInfoListData.size() > 0) {
            //add by mai 2015-3-19
            llDeviceQuickAdd.setVisibility(View.GONE);
            rlListView.setVisibility(View.VISIBLE);
            bCheck = true;
            //end add by mai 2015-3-19
        } else {
            //add by mai 2015-3-19
            llDeviceQuickAdd.setVisibility(View.VISIBLE);
            rlListView.setVisibility(View.GONE);
            bCheck = false;
            //end add by mai 2015-3-19

        }
        // end add by mai 2015-3-24

        // end add by luo 20141030


        initAlarmList();// add by luo 20141018
        updateListView();
        startAlarmMsgCheck(); // add by luo 20141016
        StartOnlineStatCheck();  // add by mai 2015-6-29	 ����豸�Ƿ�����?

    }

    /**
     * 跳转界面时的逻辑
     */
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {

            searchingProgress.setVisibility(View.GONE);  //add by mai 2015-3-23

            if (searchingProgress.getVisibility() == View.VISIBLE)  //add by mai 2015-3-34
            {
                searchingProgress.setVisibility(View.GONE);
            }

            // add by mai 2015-6-29 ����������ˢ��
            if (msg.arg1 == Defines.HANDLE_MSG_CODE_GET_VERSION_RESULT) {
                if (deviceListItemAdapter != null) {
                    deviceListItemAdapter.notifyDataSetChanged();
                }
                return;
            }
            //end add by mai 2015-6-29

            // add by luo 20150805
            if (msg.arg1 == LocalDefines.HANDLE_SHOW_WINDOW_ADD) {
                deviceIDAdd();

                return;
            }
            //end add by luo 20150805


            if (msg.arg1 == LocalDefines.DEVICE_IP_UPDATE) {// add by luo 20141118 //IPˢ��
                DeviceScanner.reset();  //ֹͣ�����߳�
                boolean isUpdate = false;

                long lNow = (new Date()).getTime();// add by luo 20141220

                isUpdate = false;

                for (int i = deviceIPList.size() - 1; i >= 0; i--) {

                    DeviceInfo info1 = deviceIPList.get(i);

                    if (info1 != null) {

                        for (int j = LocalDefines._severInfoListData.size() - 1; j >= 0; j--) {
                            if (j >= LocalDefines._severInfoListData.size()) break;
                            DeviceInfo info2 = LocalDefines._severInfoListData
                                    .get(j);

                            if (info1.getnDevID() == info2.getnDevID()) {
                                isUpdate = true;
                                info2.setStrIP(info1.getStrIP());
                                info2.setlOnLineStatChaneTime(lNow);                                                            // 20141220
                                info2.setnOnLineStat(Defines.ON_LINE_STAT_LAN);
                                info2.setnSaveType(Defines.SERVER_SAVE_TYPE_SEARCH);
                                DatabaseManager.UpdateServerInfoState(info2);
                                break;
                            }

                        }
                    }

                }

                if (deviceListItemAdapter != null && isUpdate) {
                    deviceListItemAdapter.notifyDataSetChanged();
                }
                //end add by mai 2015-6-18
            } else if (msg.arg1 == HANDLE_PREVIEW_LIST_UPDATE) {// add by luo
                // 20141029


                if (msg.arg2 == GET_PREVIEW_LIST_OK) {  //��ʾ���ȡ�ɹ�?

                    LocalDefines._demoSeverInfoListData.clear();
                    for (int i = 0; i < demoSeverInfoListDataTemp.size(); i++) {
                        LocalDefines._demoSeverInfoListData.add(demoSeverInfoListDataTemp.get(i));
                    }
                    if (LocalDefines._demoSeverInfoListData.size() > 0) {
                        LocalDefines._isNeedGetPreviewDeviceList = false;
                    }

                    System.out
                            .println("GetPreviewDeviceListThread Defines._demoSeverInfoListData.size="
                                    + LocalDefines._demoSeverInfoListData.size());// add
                    // for
                    // test
                    if (LocalDefines._nListMode == LocalDefines.LIST_MODE_DEMONSTRATE) {
                        updateDemoListView();
                    }
                }

            } else if (msg.arg1 == HANDLE_MESSAGE_UPDATE_FRESHFACE) { //�豸�б�ˢ��

                if (LocalDefines._nListMode != LocalDefines.LIST_MODE_NORMAL)
                    return;// add by luo 20141106

                Bundle data = msg.getData();
                if (data != null) {

                    int nDevID = data.getInt("dev_id");
                    String strUsername = data.getString("username");
                    String strPassword = data.getString("password");
                    Bitmap image = data.getParcelable("image");

                    if (nDevID > 0 && image != null && (LocalDefines._severInfoListData != null && LocalDefines._severInfoListData.size() > 0)) {

                        DatabaseManager.setFaceForDevID(nDevID, image, strUsername, strPassword);
                        boolean hasUpdate = false;
                        for (int i = LocalDefines._severInfoListData.size() - 1; i >= 0; i--) {
                            if (i >= LocalDefines._severInfoListData.size()) break;
                            DeviceInfo info = LocalDefines._severInfoListData.get(i);
                            if (info != null && info.isMatch(nDevID, strUsername, strPassword)) {
                                info.setFaceImage(image);
                                hasUpdate = true;
                                //
                            }
                        }
                        if (deviceListItemAdapter != null && hasUpdate) {
                            deviceListItemAdapter.notifyDataSetChanged();
                        }
                    }

                }
            } else if (msg.arg1 == HANDLE_MESSAGE_UPDATE_FRESHTIME) {// add by  ������ȡ���ؽ��?
                // luo

                //�õ�������Ϣ�Ƿ�����������
                Bundle data = msg.getData();
                if (data != null && (LocalDefines._severInfoListData != null && LocalDefines._severInfoListData.size() > 0)) {

                    int nDevID = data.getInt("dev_id");
                    int nNewMsgCount = data.getInt("msg_count");
                    String strUsername = data.getString("username");
                    String strPassword = data.getString("password");
                    long lLastFreshTime = data.getLong("last_fresh_time");
                    long lLastGetTime = data.getLong("last_get_time");

                    DatabaseManager.UpdateServerInfoMsgCount(nDevID,
                            lLastFreshTime, lLastGetTime, nNewMsgCount,
                            strUsername, strPassword);

                    // /
                    System.out.println("new AlarmFaceGettingMessageThread: " + nDevID + ", " +
                            strUsername + ", " + strPassword);//add for test

                    // /

                    for (int i = LocalDefines._severInfoListData.size() - 1; i >= 0; i--) {
                        if (i >= LocalDefines._severInfoListData.size()) break;
                        DeviceInfo info = LocalDefines._severInfoListData.get(i);
                        if (info.isMatch(nDevID, strUsername, strPassword)) {

                            info.setnNewMsgCount(nNewMsgCount);
                            info.setlLastMsgFreshTime(lLastFreshTime);
                            //
                        }

                    }

                    if (deviceListItemAdapter != null) {
                        deviceListItemAdapter.notifyDataSetChanged();
                    }

                }
                // end add by luo 20141016
            } else if (msg.arg1 == HANDLE_MSG_CODE_LOGIN_RESULT) {// �Ƿ����Ե�¼������Ϣ
                connectingDialog.dismiss();

                // �����¼���
                switch (msg.arg2) {
                    //-----------------------------------------------------界面跳转
                    case ResultCode.RESULT_CODE_SUCCESS: {// ��¼�ɹ�

                        Bundle data = msg.getData();
                        if (data == null) {
                            ShowAlert(getString(R.string.alert_title_login_failed) + "(" + getString(R.string.notice_Result_BadResult) + ")", getString(R.string.alert_connect_tips));
                            return;
                        }

                        data.putString("name", m_strName);
                        data.putString("server", m_strIP);
                        data.putString("username", m_strUsername);
                        data.putString("password", m_strPassword);
                        data.putInt("nPort", m_nPort);
                        m_nMsgGetThreadID++;
                        Intent intent = new Intent(DeviceListViewActivity.this, NVPlayerPlayActivity.class);
                        intent.putExtras(data);
                        DeviceListViewActivity.this.startActivity(intent);
                        DeviceListViewActivity.this.overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_NET_DOWN: {// ��¼ʧ��-���粻ͨ

                        ShowAlert(
                                getString(R.string.alert_title_login_failed)
                                        + "  ("
                                        + getString(R.string.notice_Result_BadResult)
                                        + ")",
                                getString(R.string.alert_connect_tips));
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_NET_POOL: {// ��¼ʧ��-�������ӳ��?
                        ShowAlert(
                                getString(R.string.alert_title_login_failed)
                                        + "  ("
                                        + getString(R.string.notice_Result_ConnectServerFailed)
                                        + ")",
                                getString(R.string.alert_connect_tips));
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_SERVER_OFFLINE: {// ��¼ʧ��-������������
                        ShowAlert(
                                getString(R.string.alert_title_login_failed)
                                        + "  ("
                                        + getString(R.string.notice_Result_ConnectServerFailed)
                                        + ")",
                                getString(R.string.alert_connect_tips));
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_VERIFY_FAILED: {// ��¼ʧ��-�û�����������
                        ShowAlert(getString(R.string.alert_title_login_failed),
                                getString(R.string.notice_Result_VerifyFailed));
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_USER_NOEXIST: {// ��¼ʧ��-�û�����������
                        ShowAlert(getString(R.string.alert_title_login_failed),
                                getString(R.string.notice_Result_UserNoExist));
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_PWD_ERROR: {// ��¼ʧ��-�û�����������
                        ShowAlert(getString(R.string.alert_title_login_failed),
                                getString(R.string.notice_Result_PWDError));
                    }
                    break;
                    case LOGIN_RESULT_CODE_FAIL_OLD_VERSON: {
                        ShowAlert(getString(R.string.alert_title_login_failed),
                                getString(R.string.notice_Result_Old_Version));
                    }
                    break;
                    default:

                        ShowAlert(
                                getString(R.string.alert_title_login_failed)
                                        + "  ("
                                        + getString(R.string.notice_Result_ConnectServerFailed)
                                        + ")",
                                getString(R.string.alert_connect_tips));
                        break;
                }

            } else if (msg.arg1 == LocalDefines.DEVICE_SEARCH_RESULT) {  //�����豸���?


                if (LocalDefines._nListMode != LocalDefines.LIST_MODE_NORMAL)
                    return;// add by luo 20141106

                pullToRefreshListView.onRefreshComplete();
                StopSearchDevice();
                DeviceInfo info = null;
                switch (msg.arg2) {
                    case LocalDefines.DEVICE_SEARCH_RESULT_OK:  //�����ɹ�

                        if (deviceList != null && deviceList.size() > 0) {
                            // //@@System.out.println("DEVICE_SEARCH_RESULT");//add for
                            // test
                            boolean bNewDevFound = false;
                            boolean bHasUpdate = false;
                            String searchResultMsg = getString(R.string.add_device);
                            for (int i = 0; i < deviceList.size(); i++) {
                                info = deviceList.get(i);
                                info.setnOnLineStat(Defines.ON_LINE_STAT_LAN); // �������Ķ����ھ���������
                                info.setlOnLineStatChaneTime(System.currentTimeMillis());
                                if (info != null && info.getnDevID() != 0) {
                                    System.out.println();//add for test
                                    bNewDevFound = true;
                                    if (!DatabaseManager.IsInfoExist(info)) {

                                        if (DatabaseManager.AddServerInfo(info)) {


                                            if (i == 0) {
                                                searchResultMsg = searchResultMsg
                                                        + info.getStrName();
                                            } else {
                                                searchResultMsg = searchResultMsg
                                                        + ", " + info.getStrName();
                                            }
                                        }
                                    } else {// ����豸�Ѵ��ڣ������һ��ip��ַ�Ͷ˿���Ϣ

                                        DatabaseManager.UpdateServerInfoState(info);
                                        bHasUpdate = true;
                                    }
                                } else {
                                    //id == 0ʱ�Ĵ���
                                }

                            }
                            if (deviceList.size() > 0) {

                                if (bHasUpdate) {
                                    //add by luo 20150714
                                    LocalDefines.reloadDeviceInfoList();

                                    //end add by luo 20150714
                                    if (deviceListItemAdapter != null) {
                                        deviceListItemAdapter.notifyDataSetChanged();
                                    }
                                }
                                if (bNewDevFound) {


                                    LocalDefines.isDeviceListSet = true;
                                    LocalDefines.nClientDeviceSettingThreadID++;


                                    Toast toast = Toast.makeText(
                                            DeviceListViewActivity.this.getApplicationContext(),
                                            searchResultMsg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                } else {
                                    Toast toast = Toast.makeText(
                                            DeviceListViewActivity.this.getApplicationContext(),
                                            getString(R.string.search_finish),
                                            Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }

                                //	StartOnlineStatCheck(); // add by mai 2015-7-2 ����״̬ˢ���߳�

                                refleshListView();
                            } else {
                                System.out.println("没有找到设备");
                                Toast toast = Toast.makeText(
                                        DeviceListViewActivity.this.getApplicationContext(),
                                        getString(R.string.no_dev_found),
                                        Toast.LENGTH_SHORT);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                            }

                        } else {
                            Toast toast = Toast.makeText(
                                    DeviceListViewActivity.this.getApplicationContext(),
                                    getString(R.string.no_dev_found),
                                    Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }

                        break;
                    case LocalDefines.DEVICE_SEARCH_RESULT_FAIL:

                        // searchTitle.setText(getString(R.string.has)+" 0 "+getString(R.string.device_found));
                        Toast toast = Toast.makeText(
                                DeviceListViewActivity.this.getApplicationContext(),
                                getString(R.string.no_dev_found),
                                Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        break;

                }

            } else if (msg.arg1 == LocalDefines.NV_DEVICE_NET_STATE_ONLINE)  //���Զ�����߳ɹ�?
            {
                int nIndex = msg.arg2;
                if (nIndex >= 0 && nIndex < LocalDefines._severInfoListData.size()) {
                    DeviceInfo info = LocalDefines._severInfoListData.get(nIndex);
                    if (info != null) {

                        if (DatabaseManager.UpdateServerInfoState(info)) {

                        }
                    }


                }
                if (deviceListItemAdapter != null) {
                    deviceListItemAdapter.notifyDataSetChanged();

                }

            }

        }
    };


    // ��½�߳���
    // �ֻ��¼�������
    /*
     * 1.���ж������������IP�������� 2.�������ip������ֱ���ķ�ʽ��¼������¼���ϵĻ��ٳ�����ת����������¼
	 * 3.������������������ת����������¼����ת�����������صĽ�����ж�����ֱ������ת��ȥ����ͼ���������ת��������ʧ�ܣ�������ֱ���ķ�ʽ��¼
	 */
    // ���ܣ���������������͵�½���󣬷��ص�½���

    class LoginThread extends Thread {
        private Handler handler;
        private int m_ThreadLoginID = 0;
        private DeviceInfo info = null;


        public LoginThread(Handler handler, DeviceInfo info, int nLoginID) {
            this.handler = handler;
            this.info = info;
            this.m_ThreadLoginID = nLoginID;

        }


        public void run() {

            if (m_ThreadLoginID == m_loginID) {
                LoginHandle deviceParam = null;
                if (info.getnSaveType() == Defines.SERVER_SAVE_TYPE_DEMO) {

                    deviceParam = LoginHelper.getDeviceParam(info, info.getStrMRServer(), info.getnMRPort());
                } else {
                    deviceParam = LoginHelper.getDeviceParam(info);
                }

                if (deviceParam != null && deviceParam.getnResult() == ResultCode.RESULT_CODE_SUCCESS) {
                    Message msg = handler.obtainMessage();
                    msg.arg1 = HANDLE_MSG_CODE_LOGIN_RESULT;
                    msg.arg2 = ResultCode.RESULT_CODE_SUCCESS;
                    Bundle data = new Bundle();
                    data.putParcelable("device_param", deviceParam);
                    msg.setData(data);
                    System.out.println("login result : " + deviceParam.isMRMode());//add for test
                    handler.sendMessage(msg);
                } else {
                    if (deviceParam != null) {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = HANDLE_MSG_CODE_LOGIN_RESULT;
                        msg.arg2 = deviceParam.getnResult();
                        handler.sendMessage(msg);
                    } else {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = HANDLE_MSG_CODE_LOGIN_RESULT;
                        msg.arg2 = ResultCode.RESULT_CODE_FAIL_SERVER_CONNECT_FAIL;

                        handler.sendMessage(msg);
                    }
                }
            }

        }
    }// end of LoginThread

    // ��ʼ�豸����
    public boolean StartSearchDevice() {
        System.out.println("StartSearchDevice");//add for test

        try {
            if (!Functions.isNetworkAvailable(DeviceListViewActivity.this
                    .getApplicationContext())) {// ���粻����

                searchingProgress.setVisibility(View.GONE);
                connectingDialog.dismiss();
                Toast toast = Toast.makeText(
                        DeviceListViewActivity.this.getApplicationContext(),
                        getString(R.string.toast_network_unreachable),
                        Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        m_nSearchID++;
        bIsSearching = true;

        closeMulticast();
        openMulticast();
        new DeviceSearchThread(m_nSearchID).start();
        return true;

    }

    // ֹͣ�豸����
    public void StopSearchDevice() {
        closeMulticast();
        bIsSearching = false;
        m_nSearchID++;
        mIsSearchingMode = false;
        pullToRefreshListView.onRefreshComplete();
        if (connectingDialog != null) {
            connectingDialog.dismiss();
        }
        DeviceScanner.reset();

    }

    // �豸�����߳�
    public class DeviceSearchThread extends Thread {


        private int nSearchID = 0;

        public DeviceSearchThread(int m_nSearchID) {
            this.nSearchID = m_nSearchID;
        }

        public void run() {

            for (int i = 0; i < 3; i++) {


                deviceList = DeviceScanner.getDeviceListFromLan();
                if (deviceList != null && deviceList.size() > 0 && m_nSearchID == nSearchID) {
                    Message msg = handler.obtainMessage();
                    msg.arg1 = LocalDefines.DEVICE_SEARCH_RESULT;
                    msg.arg2 = LocalDefines.DEVICE_SEARCH_RESULT_OK;
                    handler.sendMessage(msg);
                } else {

                    if (i >= 3 && m_nSearchID == nSearchID) {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = LocalDefines.DEVICE_SEARCH_RESULT;
                        msg.arg2 = LocalDefines.DEVICE_SEARCH_RESULT_FAIL;
                        handler.sendMessage(msg);
                    }

                }
//				
            }


        }

    }


    DatagramSocket ipuStationudpSocket = null;
    DatagramSocket ipuAPudpSocket = null;

    // �豸�����߳�
    public class IPUpdateThread extends Thread {// add by luo 20141118

        private int nTreadSearchID = 0;

        public IPUpdateThread(int nUpdateID) {
            nTreadSearchID = nUpdateID;
        }

        public void run() {

            while (nTreadSearchID == m_nIPUpdateID) {

//				System.out.println("update ip while");//add for test
//				if (relateAtivity == null) {
//					try {
//						Thread.sleep(5000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					continue;
//				} else {
                try {
                    //@@System.out.println(":isNetworkWifi 1");
                    if (!Functions.isNetworkWifi(DeviceListViewActivity.this
                            .getApplicationContext())) {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
//								e.printStackTrace();
                        }
                        continue;
                    }
                } catch (Exception e) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ie) {
                        // TODO Auto-generated catch block
//							e.printStackTrace();
                    }
                    continue;
                }

//				}
                if (bIsSearching) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
//						e.printStackTrace();
                    }
                    continue;
                }


                deviceIPList = DeviceScanner.getDeviceListFromLan();
                if (deviceIPList != null && deviceIPList.size() > 0) {
                    if (!bIsSearching && m_nSearchID == nTreadSearchID) {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = LocalDefines.DEVICE_IP_UPDATE;
                        msg.arg2 = LocalDefines.DEVICE_SEARCH_RESULT_OK;
                        handler.sendMessage(msg);
                    }
                    break;
                }


                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

    }

    // ɾ�������?
    @SuppressWarnings("deprecation")
    public void onDeviceInfoSelectChange(int nIndex, ImageButton imgButton) {

        if (LocalDefines._severInfoListData != null && nIndex >= 0
                && nIndex < LocalDefines._severInfoListData.size()) {
            DeviceInfo info = LocalDefines._severInfoListData.get(nIndex);
            if (info != null) {
                info.setCheck(!info.isCheck());
                if (imgButton != null) {
                    if (info.isCheck()) {
                        imgButton.setBackgroundDrawable(getResources()
                                .getDrawable(R.drawable.check_save_btn));
                    } else {
                        imgButton.setBackgroundDrawable(getResources()
                                .getDrawable(R.drawable.check_normal_btn));
                    }
                }
            }

            info = null;
        }

        onSelectChange();// add by luo 20141016
    }

    public void onShowAlarmMessage(int nIndex) {


    }


    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {

        if (bDemoOrDevice)  //add by mai 2015-5-11 ���ж����豸��?����ʾ��ģʽ
        {
            DeviceInfo info = LocalDefines._severInfoListData.get(arg2);
            setEditDelete(arg1, info, arg2);
        }

        return true;
    }


    /**
     * ��������������ˢ���߳�
     */
    private void StartOnlineStatCheck() {
        _nOnlineStatCheckID++;
        //@@System.out.println("StartOnlineStatCheck");//add for test
        new OnlineStatCheckThread(handler, _nOnlineStatCheckID).start();
    }


    /**
     * add by mai 2015-6-29 �豸�������Ƿ����߹���
     *
     * @author Administrator
     */
    private int _nOnlineStatCheckID = 0;
    private long _lBroadcastTime = 0;

    private class OnlineStatCheckThread extends Thread {

        byte buffer[] = new byte[Defines.CONFIG_BUFFER_SIZE_STATE];


        private Handler handler;
        private int m_nThreadID = 0;

        //��ȡ�������ù��캯��
        public OnlineStatCheckThread(Handler handler, int nThreadID) {

            this.handler = handler;
            m_nThreadID = nThreadID;
        }


        private int getStatFromMR(DeviceInfo info) {
            int nStat = LocalDefines.NV_IPC_ONLINE_CHECK_UNKNOWN;
            OutputStream writer = null;
            InputStream reader = null;
            Socket sSocket = null;

            int nConfigResultCode = 0;

            if (_nOnlineStatCheckID == m_nThreadID) {


                sSocket = Functions.connectToMRServer(null, Defines._OnLinePort, 8000);
                // end modify by luo 20141027
                if (sSocket == null) {
                    return nStat;
                }

                try {
                    if (sSocket.isConnected()) {
                        writer = sSocket.getOutputStream();
                        reader = sSocket.getInputStream();
                    } else {
                        nConfigResultCode = ResultCode.RESULT_CODE_FAIL_SERVER_CONNECT_FAIL;
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    System.out.println("����������IOʧ��");// add for test
                    nConfigResultCode = ResultCode.RESULT_CODE_FAIL_SERVER_CONNECT_FAIL;
                    if (writer != null) {
                        try {
                            writer.close();

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        }
                    }

                    writer = null;
                    if (reader != null) {
                        try {
                            reader.close();

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        }
                    }

                    reader = null;

                    if (sSocket != null) {
                        try {
                            sSocket.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        }
                    }
                    sSocket = null;
                    return nStat;
                }
//  				System.out.println("getStatFromMR: 2"+_nOnlineStatCheckID+", "+m_ThreadConfigID+", "+nConfigResultCode);//add for test
                //��ʼ��֤��¼
                if (_nOnlineStatCheckID == m_nThreadID && nConfigResultCode == 0) {//�ж��Ƿ���Ҫ���е�¼����

                    int nCMD = LocalDefines.NV_IPC_ONLINE_CHECK_REQUEST;

                    //
                    Arrays.fill(buffer, (byte) 00);
                    Functions.IntToBytes(nCMD, buffer, 0);
                    Functions.IntToBytes(Defines.OS_PHONE_TYPE, buffer, 4);
                    if (info.getStrDomain() != null) {
                        System.arraycopy(info.getStrDomain().getBytes(), 0, buffer, 8,
                                (info.getStrDomain().getBytes()).length);
                    }

                    Functions.IntToBytes(info.getnPort(), buffer, 40);
                    Functions.IntToBytes(info.getnDevID(), buffer, 44);

                    ///

                    //
//         	    		System.out.println("getRecordConfig  ����ָ��"+m_ThreadUsername.length()+" : "+m_ThreadPassword.length()+";"+(m_ThreadUsername.getBytes()).length+":"+(m_ThreadPassword.getBytes()).length);//add for test
                    //��ʼ����
                    try {
                        writer.write(buffer, 0, Defines.CONFIG_BUFFER_SIZE_STATE);
                        writer.flush();
                    } catch (IOException e3) {
                        // TODO Auto-generated catch block

                        try {
                            writer.close();
                            reader.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        nConfigResultCode = ResultCode.RESULT_CODE_FAIL_SERVER_CONNECT_FAIL;
                    }

                    //���յ�¼���?
                    Arrays.fill(buffer, (byte) 00);
                    boolean bReadOK = false;//��ȡ��¼���ok
                    for (int i = 0; i < 50; i++) {


                        try {
                            if (reader.available() < Defines.CONFIG_BUFFER_SIZE_RECEIVE) {//
                                try {
                                    Thread.sleep(20);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                continue;
                            }

                            reader.read(buffer, 0, Defines.CONFIG_BUFFER_SIZE_RECEIVE);
                            bReadOK = true;
                            break;
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                            break;
                        }
                    }

                    //		System.out.println("�豸�õ���¼���getStatFromMR: 4");//add for test
                    if (bReadOK) {

                        //�жϵ�¼���?
                        int nResultCmd = Functions.BytesToInt(buffer, 0);

                        int nResultCode = Functions.BytesToInt(buffer, 4);

                        //���ؽ��?
//         	    			ָ���֣�4byte��+���ֵ��?byte��+�豸id��4byte��(���С�?6byte)

//         	    			System.out.println("getStatFromMR: OK:"+nResultCmd);//add for test

                        if (nResultCmd == LocalDefines.NV_IPC_ONLINE_CHECK_RESPONSE) {//��¼���?

                            int nResultDevice = Functions.BytesToInt(buffer, 8);
//         	    				System.out.println("getStatFromMR ���ս��? OK:"+nResultCmd+"_"+nResultCode +","+nResultDevice+", "+info.getnDevID());//add for test


                            if (nResultDevice == info.getnDevID()) {
                                nStat = nResultCode;
                            }


                        }
                        //
                    }

                }


            }

            if (sSocket != null && sSocket.isConnected()) {
                try {
                    sSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
// 					e.printStackTrace();
                }
            }
            sSocket = null;
            return nStat;
        }

        private boolean checkStatFromLan() {
            boolean bResult = false;

            return bResult;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub

            boolean bLanResult = false;
            int nStat = 0;
            while (_nOnlineStatCheckID == m_nThreadID) {

                if (bIsSearching) continue;


                if (LocalDefines._severInfoListData != null && LocalDefines._severInfoListData.size() > 0) {

                    //1.���ù㲥������������������?0�����һ�ξ�������?
                    if (System.currentTimeMillis() - _lBroadcastTime >= 60000) {

                        bLanResult = checkStatFromLan();
                        if (bLanResult) {//������㲥���ɹ������¹㲥ʱ��?
                            _lBroadcastTime = System.currentTimeMillis();
                        }

                    }

                    //2.�����������ߵ��豸�Ƿ���������
                    for (int i = LocalDefines._severInfoListData.size() - 1; i >= 0 && _nOnlineStatCheckID == m_nThreadID; i--) {


                        if (bIsSearching || i >= LocalDefines._severInfoListData.size()) break;

                        DeviceInfo info = LocalDefines._severInfoListData.get(i);

                        if (info != null &&
                                ((System.currentTimeMillis() - info.getlOnLineStatChaneTime() >= 50000)
                                        || info.getnOnLineStat() == Defines.ON_LINE_STAT_UNKNOW
                                        || info.getnOnLineStat() == Defines.ON_LINE_STAT_READY)) {
                            nStat = getStatFromMR(info);

                            //@@System.out.println("getStatFromMR:"+info.getnDevID()+", "+nStat);//add for test
                            if (System.currentTimeMillis() - info.getlOnLineStatChaneTime() >= 50000) {
                                if (nStat != LocalDefines.NV_IPC_ONLINE_CHECK_UNKNOWN) {


                                    if (nStat == LocalDefines.NV_IPC_ONLINE_CHECK_ONLINE) {
                                        info.setnOnLineStat(Defines.ON_LINE_STAT_WAN);
                                    } else if (nStat == LocalDefines.NV_IPC_ONLINE_CHECK_OFFLINE) {
                                        info.setnOnLineStat(Defines.ON_LINE_STAT_OFF);
                                    }
                                    info.setlOnLineStatChaneTime(System.currentTimeMillis());
                                    if (_nOnlineStatCheckID == m_nThreadID && !bIsSearching) {
                                        Message msg = handler.obtainMessage();
                                        msg.arg1 = LocalDefines.NV_DEVICE_NET_STATE_ONLINE;
                                        msg.arg2 = i;
                                        handler.sendMessage(msg);
                                    }


                                } else {
                                    info.setlOnLineStatChaneTime(System.currentTimeMillis());
                                    info.setnOnLineStat(Defines.ON_LINE_STAT_READY);
                                    if (_nOnlineStatCheckID == m_nThreadID && !bIsSearching) {
                                        Message msg = handler.obtainMessage();
                                        msg.arg1 = LocalDefines.NV_DEVICE_NET_STATE_ONLINE;
                                        msg.arg2 = i;
                                        handler.sendMessage(msg);
                                    }
                                }
                            }

                        }

                    }

                    //�ӳ�60����ˢ��
                    try {
                        sleep(10000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        }

    }

    public void openMulticast() {
        try {

            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            multicastLock = wifiManager.createMulticastLock("multicast");
            multicastLock.acquire();
        } catch (Exception e) {
            //@@System.out.println("openMulticast error");//add for test
            multicastLock = null;
        }
    }

    public void closeMulticast() {
        if (multicastLock != null) {
            multicastLock.release();
            multicastLock = null;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return false;
    }

}
